import java.util.*;

/**
 * @author LKQ
 * @date 2022/3/8 16:35
 * @description 二分查找
 */
public class FormalSolution {
    public static void main(String[] args) {
        TreeNode t4 = new TreeNode(4), t5 = new TreeNode(5),
                t6 = new TreeNode(6), t3 = new TreeNode(3, t6, null),
                t2 = new TreeNode(2, t4, t5), t1 = new TreeNode(1, t2, t3);
        FormalSolution solution = new FormalSolution();
        solution.countNodes(t1);
    }
    public int countNodes(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int level = 0;
        TreeNode node = root;
        // 完全二叉树中，一直向左求树的深度
        while (node.left != null) {
            level++;
            node = node.left;
        }
        // 该层的节点编号范围
        int low = 1 << level, high = (1 << (level + 1)) - 1;
        while (low < high) {
            int mid = (high - low + 1) / 2 + low;
            if (exists(root, level, mid)) {
                low = mid;
            } else {
                high = mid - 1;
            }
        }
        return low;
    }

    public boolean exists(TreeNode root, int level, int k) {
        int bits = 1 << (level - 1);
        TreeNode node = root;
        while (node != null && bits > 0) {
            if ((bits & k) == 0) {
                node = node.left;
            } else {
                node = node.right;
            }
            bits >>= 1;
        }
        return node != null;
    }
}
